package ldk.apps.adbconnections.handlers

import android.text.TextUtils
import android.util.ArrayMap
import android.util.Log
import android.webkit.MimeTypeMap
import ldk.apps.adbconnections.ErrorCode
import ldk.apps.adbconnections.beans.AnyResult
import ldk.apps.adbconnections.beans.FileBean
import java.io.File

/**
 * 所有关于文件File操作的指令
 * Created by ldkxingzhe@163.com on 2018/2/5.
 */

fun mimeTypeFromExtension(file: File): String?{
    val extension = file.extension
    if (TextUtils.isEmpty(extension))
        return null
    val customType: String? = when(extension){
        "db" -> "custom/db"
        "sum" -> "custom/sum"
        "db-journal" -> "custom/db-journal"
        "part" -> "custom/part"
        "tmp", "temp", "temp!" -> "custom/tmp"
        else -> null
    }
    if (!TextUtils.isEmpty(customType)) return customType
    val mimeType =  MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
    if (!TextUtils.isEmpty(mimeType)) return mimeType
    return when(extension){
        "avi" -> "video/avi"
        "exe" -> "application/octet-stream"
        "gif" -> "image/gif"
        else -> null
    }
}

class FileListHandler: BaseHandler() {

    override val ACTION: Short = 0x55

    fun action(filePath: String, containSize: Boolean = false): Any?{
        val file = File(filePath)
        if (!file.exists()){
            return AnyResult.withErrorCode(ErrorCode.NOT_FOUND)
        }
        val childrenFiles = file.listFiles()
        return childrenFiles?.map {
            val bean = FileBean(it.name)
            bean.isHidden = it.isHidden
            if (it.isDirectory){
                bean.type = "dict"
            }else{
                bean.type = mimeTypeFromExtension(it)
                bean.size = it.length().toInt()
            }
            bean.createTime = it.lastModified()
            bean
        }
    }
}

class FileContentHandler: BaseHandler(){
    override val ACTION: Short = 0x56

    fun action(filePath: String, maxSize: Int = 1024): ByteArray{
        val file = File(filePath)
        val inputStream = file.inputStream()
        val buffer = ByteArray(Math.min(file.length().toInt(), maxSize))
        inputStream.read(buffer)
        inputStream.close()
        return buffer
    }
}